﻿using CoreLims.Models.CoreLims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Scripting.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using static IronPython.Modules._ast;
using static StatisticalQuery.Common;

namespace CoreLims.Controllers
{
    [Authorize]
    public class CommonController : Controller
    {
        private readonly CoreLimsContext dbContext;
        private readonly IWebHostEnvironment _hostingEnvironment;
        public CommonController(CoreLimsContext context, IWebHostEnvironment hostingEnvironment)
        {
            dbContext = context;
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        public ViewResult StatisticalQuerys() => View();

        [HttpPost]
        public JsonResult getGlobalsContainName(string KyeName)
        {
            var list = Common.getGlobalsContainName(dbContext, KyeName);
            return Json(list);
        }

        #region 提醒

        [HttpPost]
        public string CheckRemind() // 检查是否有我的提醒
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            if (dbContext.Remind.Where(s => s.UserId == user.Id && s.ReadTime == null).Count() > 0)
                return "true";
            else
                return "false";
        }

        [HttpPost]
        public JsonResult GetMyRemind() // 登录用户获取自己的提醒列表
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var list = dbContext.Remind.Where(s => s.UserId == user.Id && s.ReadTime == null)
                        .OrderByDescending(s => s.CreateTime)
                        .Select(s => new { s.Id, s.Title, s.Content, s.CreateTime, s.WorkFlowId})
                        .ToList();
            return Json(list);
        }

        /// <summary>
        /// 系统版本界面
        /// </summary>
        /// <returns></returns>
        public ViewResult LimsVersion() => View();

        #endregion

        #region 文件相关

        [HttpPost]
        public ViewResult ManageFile(string Domain, string DomainId, string ModalID)
        {
            ViewData["Domain"] = Domain;
            ViewData["DomainId"] = DomainId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult EditTextContent(string Domain, string DomainId, string ModalID)
        {
            ViewData["Domain"] = Domain;
            ViewData["DomainId"] = DomainId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public ViewResult UploadDisposable(string Operation, string ModalID)
        {
            ViewData["Operation"] = Operation;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public string UploadFileSave()
        {
            try
            {
                var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
                string re = "";
                if (Request.Form.Files.Count != 0)
                {
                    Microsoft.Extensions.Primitives.StringValues Domain, DomainId;
                    Request.Form.TryGetValue("Domain", out Domain);
                    Request.Form.TryGetValue("DomainId", out DomainId);

                    foreach (var fileItem in Request.Form.Files)
                    {
                        if (fileItem.Length > 0)
                        {
                            var st = Common.UploadFile.AddUploadFile(dbContext, fileItem, Domain[0], DomainId[0], user.Id, user.FullName);
                            re = st.Result;
                        }
                    }
                }

                if (re == "")
                    return "请先选择需要上传的文件！";
                else
                    return re;
            } catch (Exception ex) { return ex.ToString(); }
        }

        [HttpPost]
        public string UploadUserImg() // 上传用户头像
        {
            string re = "";
            string savePath = _hostingEnvironment.WebRootPath;
            if (Request.Form.Files.Count != 0)
            {
                Microsoft.Extensions.Primitives.StringValues Domain, DomainId;
                Request.Form.TryGetValue("Domain", out Domain);
                Request.Form.TryGetValue("DomainId", out DomainId);

                foreach (var fileItem in Request.Form.Files)
                {
                    if (fileItem.Length > 0)
                    {
                        var st = Common.UploadFile.AddUserImg(dbContext, fileItem, savePath, Domain[0], DomainId[0]);
                        re = st.Result;
                    }
                }
            }

            if (re == "")
                return "请先选择需要上传的文件！";
            else
                return re;
        }

        [HttpPost]
        public string UploadUserSignature() // 上传用户签名
        {
            string re = "";
            string savePath = _hostingEnvironment.WebRootPath;
            if (Request.Form.Files.Count != 0)
            {
                Microsoft.Extensions.Primitives.StringValues Domain, DomainId;
                Request.Form.TryGetValue("Domain", out Domain);
                Request.Form.TryGetValue("DomainId", out DomainId);

                foreach (var fileItem in Request.Form.Files)
                {
                    if (fileItem.Length > 0)
                    {
                        var st = Common.UploadFile.AddUserSignature(dbContext, fileItem, savePath, Domain[0], DomainId[0]);
                        re = st.Result;
                    }
                }
            }

            if (re == "")
                return "请先选择需要上传的文件！";
            else
                return re;
        }

        [HttpPost]
        public string DeleteUploadFile(string Ids)
        {
            return Common.UploadFile.DeleteUploadFile(dbContext, Ids);
        }

        public JsonResult GetUploadFileList(string Domain, string DomainId)
        {
            var list = Common.UploadFile.getIdsByDomain(dbContext, Domain, DomainId);
            return Json(list);
        }

        public JsonResult GetUploadFile(string FileId)
        {
            var list = Common.UploadFile.getUploadFile(dbContext, FileId);
            return Json(list);
        }

        [HttpPost]
        public string postDeleteFile(string FileId)
        {
            return Common.UploadFile.DeleteUploadFile(dbContext, FileId);
        }

        /// <summary>
        /// 该函数既可以接收ajax请求，也可以接收XMLHttpRequest()请求。参数只有一个，就是需要下载的文件ID
        /// </summary>
        /// <param name="downloadFileId"></param>
        /// <returns></returns>
        [HttpPost]
        public FileResult postDownloadFile(string downloadFileId)
        {
            Microsoft.Extensions.Primitives.StringValues fileId;
            Request.Form.TryGetValue("downloadFileId", out fileId);
            if (!string.IsNullOrEmpty(fileId))
                downloadFileId = fileId;

            var uf = Common.UploadFile.getUploadFile(dbContext, downloadFileId);
            var path = uf.getPath(dbContext);
            string fileName = path + "\\" + uf.Id + "." + uf.FileType;

            var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            return File(fileStream, "application/octet-stream", uf.FileName); // "application/octet-stream"  "application/vnd.ms-excel" "application/msword"
        }

        [HttpPost]
        /// <summary>
        /// 下载指定位置的文件
        /// </summary>
        /// <param name="type">下载文件的类别</param>
        /// <param name="fileName">路径+文件名</param>
        /// <param name="isTemp">是否包含指定目录下TEMP目录</param>
        /// <returns></returns>
        public FileResult DownloadFile(string pathName, string fileName, string isTemp)
        {
            Microsoft.Extensions.Primitives.StringValues _pathName, _fileName, _isTemp;
            Request.Form.TryGetValue("type", out _pathName); // 获取 formData 中传递过来的参数
            Request.Form.TryGetValue("fileName", out _fileName);
            Request.Form.TryGetValue("isTemp", out _isTemp);

            if (!string.IsNullOrEmpty(_pathName))
                pathName = _pathName;
            if (!string.IsNullOrEmpty(_fileName))
                fileName = _fileName;
            if (!string.IsNullOrEmpty(_isTemp))
                isTemp = _isTemp;

            var dir = Common.getGlobalKeyValue(dbContext, pathName);
            string file;
            if(isTemp.ToLower() == "true")
                file = dir + "\\TEMP\\" + fileName;
            else
                file = dir + fileName;
            var name = file.Split('\\');

            var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            return File(fileStream, "application/octet-stream", name[name.Length - 1]);
        }

        [HttpPost]
        public string UpdateFileName(string Id, string newFileName) // 修改文件原名称
        {
            return Common.UploadFile.UpdateFileName(dbContext, Id, newFileName);
        }

        [HttpPost]
        public string GetTextContent(string Domain, string DomainId) // 获得文本文件的内容
        {
            var path = Common.getGlobalKeyValue(dbContext, Domain + "_Path");
            var fileName = path + "\\" + DomainId + ".txt";

            if (System.IO.File.Exists(fileName))
            {
                StreamReader sw = new StreamReader(fileName);
                string st = sw.ReadToEnd();
                sw.Close();
                return st;
            }
            else  // 如果没有则立即创建一个新文件，供后续保存文件内容使用。
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                if (!dir.Exists)
                    Directory.CreateDirectory(path);

                StreamWriter sw = new StreamWriter(fileName);
                sw.Close();
                return "";
            }
        }

        [HttpPost]
        public string SaveTextContent(string Domain, string DomainId, string Content) // 保存文本文件的内容
        {
            var path = Common.getGlobalKeyValue(dbContext, Domain + "_Path");
            var fileName = path + "\\" + DomainId + ".txt";

            if (System.IO.File.Exists(fileName))
            {
                StreamWriter sw = new StreamWriter(fileName);
                sw.Write(Content);
                sw.Close();
                return "保存成功！";
            }
            else 
                return "";

        }

        #endregion

        #region 单位和转换因子
        [Authorize(Roles = "Admin")]
        public ViewResult Unit() => View();

        [HttpPost]
        public string DeleteUnit(string Code)
        {
            return Common.Unit.DeleteUnit(dbContext, Code);
        }

        [HttpGet]
        [HttpPost]
        public string postAddUnit(string jsonUnit)
        {
            CommonUnit unit = JsonConvert.DeserializeObject<CommonUnit>(jsonUnit);  //反序列化，字符串转换为类
            var st = unit.AddUnit(dbContext);
            return st;
        }

        [HttpGet]
        [HttpPost]
        public ViewResult AddUnit()
        {
            return View(Common.Unit.getUnitList(dbContext).Distinct(new Common.UnitTypeCompare()));
        }

        [HttpPost]
        public ViewResult AddFactor()
        {
            return View(Common.Unit.getUnitList(dbContext).Distinct(new Common.UnitTypeCompare()));
        }

        [HttpPost]
        public string postAddConversionFactor(string Code, string AscFactor, string DescFactor, string TargetCode)
        {
            CommonConversionFactor new1 = new CommonConversionFactor();
            CommonConversionFactor new2 = new CommonConversionFactor();

            new1.Code = Code;
            new1.TargetCode = TargetCode;
            new1.Factor = decimal.Parse(AscFactor);

            new2.Code = TargetCode;
            new2.TargetCode = Code;
            new2.Factor = decimal.Parse(DescFactor);

            var s1 = Common.ConversionFactor.AddConversionFactor(dbContext, new1);
            var s2 = Common.ConversionFactor.AddConversionFactor(dbContext, new2);
            return "添加成功！";
        }

        [HttpPost]
        public JsonResult GetConversionFactorList(string SourceCode)
        {
            var list = Common.Unit.getConversionFactorList(dbContext, SourceCode);
            return Json(list);
        }

        [HttpPost]
        public string DeleteFactor(string Id)
        {
            return Common.ConversionFactor.DeleteConversionFactor(dbContext, Id);
        }

        [HttpPost]
        public JsonResult GetUnitByType(string Type, string limit, string offset)
        {
            var list = Common.Unit.getUnitList(dbContext).Where(m => m.Type == Type)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = Common.Unit.getUnitList(dbContext).Where(m => m.Type == Type).ToList().Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetUnitByTypeall(string Type)
        {
            var list = Common.Unit.getUnitList(dbContext).Where(m => m.Type == Type).ToArray();

            return Json(list);
        }

        [HttpGet]
        [HttpPost]
        public JsonResult GetUnitType()
        {
            var list = Common.Unit.getUnitList(dbContext).Distinct(new Common.UnitTypeCompare());
            return Json(list);
        }

        /// <summary>
        /// 根据类型，返回对应类型的单位代码数组
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetUnitCodeByType(string Type)
        {
            var list = Common.Unit.getUnitList(dbContext).Where(m => m.Type == Type).Select(s => new { s.Code }).ToList();
            return Json(list);
        }

        #endregion

        #region 实验室和工作组
        [Authorize(Roles = "Admin")]
        public ViewResult SiteGroup()
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            ViewData["LoginUserName"] = user.FullName + "：" + DateTime.Now.ToString("yyyy年MM月dd, dddd");
            return View(Common.SiteGroup.getSiteGroupList(dbContext).Distinct(new Common.SiteGroupSiteCompare()));
        }

        [HttpPost]
        public ViewResult AddSiteGroup()
        {
            return View(Common.SiteGroup.getSiteGroupList(dbContext).Distinct(new Common.SiteGroupSiteCompare()));
        }

        [HttpPost]
        public ViewResult GroupAndUser(string SiteGroupID)
        {
            ViewData["SiteGroupID"] = SiteGroupID;
            return View();
        }

        [HttpPost]
        public string postAddSiteGroup(string jsonStr)
        {
            CommonSiteGroup siteGroup = JsonConvert.DeserializeObject<CommonSiteGroup>(jsonStr);  //反序列化，字符串转换为类
            var st = Common.SiteGroup.AddSiteGroup(dbContext, siteGroup);
            return st;
        }

        [HttpPost]
        public string deleteSiteGroup(string Id)
        {
            return Common.SiteGroup.DeleteSiteGroup(dbContext, Id);
        }

        [HttpPost]
        public JsonResult GetSiteGroupList()
        {
            var list = Common.SiteGroup.getSiteGroup(dbContext);
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetGroupUsers(string SiteGroupId, string Exclude)
        {
            var list = dbContext.GroupUser.Where(s => s.GroupId == SiteGroupId).ToList();

            string[] array = new string[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                array[i] = list[i].UserId;
            }

            if (Exclude == "true")
            {
                var users = dbContext.User.Where(s => !array.Contains(s.Id))
                    .Select(s => new { s.Id, s.FullName, s.IdentityName })
                    .ToArray();
                return Json(users);
            }
            else
            {
                var users = dbContext.User.Where(s => array.Contains(s.Id))
                    .Select(s => new { s.Id, s.FullName, s.IdentityName })
                    .ToArray();
                return Json(users);
            }
        }

        [HttpPost]
        public string AddGroupUsers(string SiteGroupId, string Users)
        {
            try
            {
                var list = Users.Split(',');
                foreach (string s in list)
                {
                    var guser = new CommonGroupUser();
                    guser.GroupId = SiteGroupId;
                    guser.UserId = s;
                    dbContext.Add(guser);
                }
                dbContext.SaveChanges();
                return "组用户添加成功！";
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
        }

        [HttpPost]
        public string RemoveGroupUsers(string SiteGroupId, string Users)
        {
            try
            {
                var list = Users.Split(',');
                foreach (string st in list)
                {
                    var guser = dbContext.GroupUser.Where(s => s.GroupId == SiteGroupId && s.UserId == st).FirstOrDefault();
                    dbContext.Remove(guser);
                }
                dbContext.SaveChanges();
                return "组用户删除成功！";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region 客户
        [Authorize(Roles = "Admin")]
        public ViewResult Supplier()
        {
            return View(Common.Supplier.getSupplierList(dbContext).Distinct(new Common.SupplierSupplierTypeCompare()));
        }

    [HttpPost]
        public ViewResult AddSupplier(string SupplierId)
        {
            ViewData["SupplierId"] = SupplierId;
            return View(Common.Supplier.getSupplierList(dbContext).Distinct(new Common.SupplierSupplierTypeCompare()));
        }

        [HttpPost]
        public string postAddSupplier(string jsonStr)
        {
            CommonSupplier supplier = JsonConvert.DeserializeObject<CommonSupplier>(jsonStr);  //反序列化，字符串转换为类
            var st = supplier.AddSupplier(dbContext);
            return st;
        }

        [HttpPost]
        public string postUpdateSupplier(string jsonStr)
        {
            CommonSupplier supplier = JsonConvert.DeserializeObject<CommonSupplier>(jsonStr);  //反序列化，字符串转换为类
            var st = supplier.UpdateSupplier(dbContext);
            return st;
        }

        [HttpPost]
        public JsonResult GetSupplierList()
        {
            var list = Common.Supplier.getSupplierList(dbContext);
            return Json(list);
        }

        [HttpPost]
        public JsonResult SupplierBandToSelect(string Type) // 下拉列表框控件绑定客户
        {
            var list = Common.Supplier.getSupplierList(dbContext)
                .Where(s => s.SupplierType == Type)
                .Select(s => new { s.SupplierId, s.SupplierName });
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetSupplier(string SupplierId)
        {
            var supplier = Common.Supplier.getSupplier(dbContext, SupplierId);
            return Json(supplier);
        }

        [HttpPost]
        public string deleteSupplier(string SupplierId)
        {
            return Common.Supplier.DeleteSupplier(dbContext, SupplierId);
        }
        #endregion

        #region 环境监测相关

        [Authorize(Roles = "Admin")]
        public ViewResult AreaAndLocation() => View();

        [Authorize(Roles = "Admin")]
        public ViewResult Monitoring() => View();

        public ViewResult EnvMonitoring() => View();

        [HttpPost]
        public ViewResult AddMonitoring(string MonitoringId, string ModalID)
        {
            ViewData["MonitoringId"] = MonitoringId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public JsonResult GetMonitoringType() //获取 type 数组
        {
            var list = Common.Env.getMonitoringList(dbContext)
                .Distinct(new Common.MonitoringTypeCompare()).Select(s => new { s.Type });
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetAreaAndLocationType() //获取 type 数组
        {
            var list = Common.Env.getAreaList(dbContext)
                .Distinct(new Common.AreaAndLocationTypeCompare()).Select(s => new { s.Type });
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetLocationByType(string Type) // 获得指定类型的位置列表
        {
            var list = Common.Env.getLocationList(dbContext).Where(s => s.Type == Type);

            var re = new List<String[]>();
            foreach (var item in list)
            {
                var location = new String[2] { item.Id, Common.Env.getDirectoryStr(dbContext, item.Id) };
                re.Add(location);
            }
            //re.ToList();
            return Json(re);
        }

        [HttpPost]
        public JsonResult GetMonitoringListByType(string Type, string limit, string offset)
        { 
            var list = Common.Env.getMonitoringList(dbContext)
                .Where(m => m.Type == Type)
                .OrderBy(s => s.Name)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = Common.Env.getMonitoringList(dbContext).Where(m => m.Type == Type).ToList().Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public JsonResult GetMonitoringNameListByType(string Type)
        {
            var list = Common.Env.getMonitoringList(dbContext)
                .Where(m => m.Type == Type)
                .OrderBy(s => s.Name)
                .Select(s => new { s.Id, s.Name });
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetMonitoringByAreaAndLocationId(string AreaAndLocationId)
        {
            var aal = Common.Env.getAreaAndLocation(dbContext, AreaAndLocationId);
            var mon = dbContext.Monitoring.Where(s => s.Id == aal.EnvMonitoringId).ToList();
            return Json(mon);
        }

        [HttpPost]
        public JsonResult GetRecordByAreaAndLocationId(string AreaAndLocationId, string limit, string offset)
        {
            var list = dbContext.MonitoringRecord.Where(s => s.AreaAndLocationId == AreaAndLocationId)
                .OrderByDescending(s => s.RecordTime)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = dbContext.MonitoringRecord.Where(s => s.AreaAndLocationId == AreaAndLocationId).ToList().Count;
            res.rows = list;

            return Json(res);
        }

        [HttpPost]
        public string postAddMonitoring(string jsonStr)
        {
            var monitoring = JsonConvert.DeserializeObject<Env.Monitoring>(jsonStr);  //反序列化，字符串转换为类
            dbContext.Monitoring.Add(monitoring);
            dbContext.SaveChanges();
            return "监测标准添加成功！";
        }

        [HttpPost]
        public string UpdateMonitoring(string jsonStr)
        {
            var other = JsonConvert.DeserializeObject<Env.Monitoring>(jsonStr);  //反序列化，字符串转换为类
            var monitoring = dbContext.Monitoring.Where(s => s.Id == other.Id).FirstOrDefault();
            monitoring.Copy(other);
            dbContext.Update(monitoring);
            dbContext.SaveChanges();
            return "监测标准更新成功！";
        }

        [HttpPost]
        public string UpdateAreaAndLocationEnv(string AreaAndLocationId, string EnvMonitoringId, string EnvMonitoringName)
        {
            var aal = Common.Env.getAreaAndLocation(dbContext, AreaAndLocationId);
            return aal.UpdateEnv(dbContext, EnvMonitoringId, EnvMonitoringName);
        }

        [HttpPost]
        public string DelMonitoring(string MonitoringId)
        {
            var aal = dbContext.AreaAndLocation.Where(s => s.EnvMonitoringId == MonitoringId).FirstOrDefault();
            if (aal != null)
                return "监测标准已关联区域或位置：" + aal.Name + " 不能删除！";

            var mon = dbContext.Monitoring.Where(s => s.Id == MonitoringId).FirstOrDefault();
            dbContext.Remove(mon);
            dbContext.SaveChanges();
            return "监测标准删除成功！";
        }

        [HttpPost]
        public string CreateArea(string jsonStr)
        {
            var aal = JsonConvert.DeserializeObject<Env.AreaAndLocation>(jsonStr);
            return Common.Env.CreateArea(dbContext, aal);
        }

        [HttpPost]
        public string CreateLocation(string jsonStr)
        {
            var aal = JsonConvert.DeserializeObject<Env.AreaAndLocation>(jsonStr);
            return Common.Env.CreateLocation(dbContext, aal);
        }

        [HttpPost]
        public string CreateMonitoringRecord(string jsonStr)
        {
            try
            {
                var mr = JsonConvert.DeserializeObject<Env.MonitoringRecord>(jsonStr);
                var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
                mr.RecordPersonId = user.Id;
                mr.RecordPersonName = user.FullName;
                return Common.Env.CreateMonitoringRecord(dbContext, mr);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [HttpPost]
        public string GetAreaAndLocationText(string AreaAndLocationId)
        {
            try
            {
                return Common.Env.getDirectoryStr(dbContext, AreaAndLocationId);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [HttpPost]
        public JsonResult GetAreaAndLocationRoots() // 获取顶级区域列表
        {
            var first = Common.Env.getAreaAndLocationRoots(dbContext)
                .OrderBy(s => s.Name)
                .Select(s => new { s.Id, s.Name, s.Type, s.IsArea })
                .ToArray();

            return Json(first);
        }

        [HttpPost]
        public JsonResult GetEnvAreaAndLocation() // 获取需要进行环境监测的区域和位置
        {
            var first = Common.Env.getEnvAreaAndLocation(dbContext)
                .OrderByDescending(s => s.IsArea)
                .Select(s => new { s.Id, s.Name, s.Type, s.IsArea })
                .ToArray();

            return Json(first);
        }

        [HttpPost]
        public JsonResult GetAreaAndLocationByParentId(string Id) // 获取指定区域下的区域和位置列表
        {
            var List = Common.Env.GetAreaAndLocationByParentId(dbContext, Id);
            if (List == null)
                return Json(null);
            else
            {
                var result = new Common.PageHelper();
                result.rows = List.ToArray();
                result.total = Common.Env.getLevel(dbContext, Id); // 此处 total 不是总数，是路径深度

                return Json(result);
            }
        }

        [HttpPost]
        public JsonResult GetAreaType()
        {
            var list = Common.Env.getAreaList(dbContext).Distinct(new Common.AreaAndLocationTypeCompare()).Select(s => new { s.Type }).ToList();
            return Json(list);
        }

        [HttpPost]
        public JsonResult GetLocationType()
        {
            var list = Common.Env.getLocationList(dbContext).Distinct(new Common.AreaAndLocationTypeCompare()).Select(s => new { s.Type }).ToList();
            return Json(list);
        }

        [HttpPost]
        public string  GetDirectoryStr(string AreaAndLocationId)
        {
            if (AreaAndLocationId == null) 
                return null;

            var st = Common.Env.getDirectoryStr(dbContext, AreaAndLocationId);
            return st;
        }

        [HttpPost]
        public string DelAreaAndLocation(string AreaAndLocationId)
        {
            return Common.Env.DelAreaAndLocation(dbContext, AreaAndLocationId);
        }

        #endregion

        #region 设备管理公共操作

        [HttpPost]
        public ViewResult AddUsageRecord(string ModalID, string EqId) // 如果没传入 EqId，表明是导入数据
        {
            ViewData["EqId"] = EqId;
            ViewData["ModalID"] = ModalID;
            return View();
        }

        [HttpPost]
        public string CreatUsageRecord(string jsonStr) // 新建设备使用记录
        {
            var usage = JsonConvert.DeserializeObject<EqUsageRecord>(jsonStr);  //反序列化，字符串转换为类
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var eq = CoreLims.Models.CoreLims.Eq.getEquipment(dbContext, usage.EqId);

            usage.EqType = eq.Type;
            usage.EqName = eq.Name;
            usage.PersonName = user.FullName;
            usage.PersonId = user.Id;
            if (!usage.SetDuration())
                return "结束时间大于开始时间，请重新设定！";

            dbContext.UsageRecord.Add(usage);
            dbContext.SaveChanges();
            return "设备使用记录添加成功！";
        }

        #endregion

        #region 统计查询

        [HttpPost]
        public ViewResult GetStatisticalQueryCshtml(string QueryName)
        {
            return View("/Views/Common/StatisticalQuery/" + QueryName + ".cshtml");
        }

        [HttpPost]
        public JsonResult CreateStatisticalQuery(string QueryName, string parameters)
        {
            try
            {
                var con = dbContext.Database.GetConnectionString();
                var list = StatisticalQuery.Common.Create(con, QueryName, parameters);
                return Json(list);
            }
            catch (Exception ex) { return Json(ex.Message); }
        }

        #endregion

    }
}
